<?php

namespace Biblibase\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Response;
use Biblibase\UserBundle\Entity\User;
use Biblibase\UserBundle\Form\UserType;

class UserController extends Controller
{
	
	 public function ajoutAction()
	 {
	 	 $user = new User();
  		 $form = $this->createForm(new UserType, $user);
 
  		 $request = $this->get('request');
  		 if ($request->getMethod() == 'POST') {
    		$form->bind($request);
 
    		 	if ($form->isValid()) {
      			$em = $this->getDoctrine()->getManager();
      			$em->persist($user);
      			$em->flush();
 
      			$return=array("error"=>"false", "message"=>"Utilisateur créé");
		 			$return=json_encode($return);
		 			return new Response($return,200,array('Content-Type'=>'application/json'));
    			}
  		  }
 
  		return $this->render('::form.html.twig', array(
    		'form' => $form->createView(),
    		'route' => $this->generateUrl('biblibase_user_ajout')
  		));
	 	 
	 }

	 public function suppressionAction()
	 {
	 
	 }
	 
	 public function loginAction()
  	 {

    	if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')) {
    		
      	return $this->redirect($this->generateUrl('biblibase_site_consultation'));
    	}
 
    	$request = $this->getRequest();
    	$session = $request->getSession();
 
    	
    	if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
      	$error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
    	} else {
      	$error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
      	$session->remove(SecurityContext::AUTHENTICATION_ERROR);
    	}
 
   	return $this->render('BiblibaseUserBundle:User:index.html.twig', array( 
      'last_username' => $session->get(SecurityContext::LAST_USERNAME),
      'error'         => $error,
    ));
  }

}
